package com.zmj.dubbo.registry;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author zhangmj
 * @date 2018/9/22 10:41
 */
@Service("iServiceDiscovery")
public class ServiceDiscoveryImpl implements IServiceDiscovery {

    @Autowired
    ZkConfig zkConfig;

    List<String> lists = new ArrayList<String>();
    private CuratorFramework curatorFramework;

    @PostConstruct
    public void init(){
        curatorFramework = CuratorFrameworkFactory.builder().connectString(zkConfig.getZkHost()).sessionTimeoutMs(4000).
                retryPolicy(new ExponentialBackoffRetry(1000,5,5000)).build();
        // 客户端已经连接上zk的服务端了
        curatorFramework.start();
    }

    @Override
    public String discover(String serviceName) {
        // 根据 serviceName进行查找
        String path = zkConfig.getZkRootPath() + "/" + serviceName;
        try {
            lists = curatorFramework.getChildren().forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return lists.get(0);
    }
}
